from django.contrib.staticfiles.views import serve
from django.shortcuts import render
from django.utils.dateparse import postgres_interval_re
from rest_framework.response import Response
from rest_framework.views import APIView

from cart.models import CartModel
from cart.ser import CartSer
from course.models import CourseModel01
from course.ser import CourseSer
from home.models import CategoryModel
from utils.Authentication import MyAuthenticate


# Create your views here.
class CartAddView(APIView):
    authentication_classes = [MyAuthenticate]
    def post(self,request):
        carts = CartModel.objects.filter(user=request.data.get('user'),goods=request.data.get('goods')).first()
        if carts:
            return Response({"msg":"课程重复了"})
        ser = CartSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg":"添加成功"})
        else:
            return Response({"msg":ser.errors})
class CartAll(APIView):
    authentication_classes = [MyAuthenticate]
    def get(self,request):
        carts = CartModel.objects.filter(user=request.query_params.get('id'))
        if carts:
            ser = CartSer(carts,many=True)
        return Response({"msg": "ok","data":ser.data})
class CartDel(APIView):
    authentication_classes = [MyAuthenticate]
    def delete(self,request):
        CartModel.objects.filter(id=request.query_params.get('id')).delete()
        return Response({"msg":"删除成功","code":200})
class CartOne(APIView):
    authentication_classes = [MyAuthenticate]
    def put(self,request):
        id = request.data.get('id')
        selected = request.data.get('selected')
        cart = CartModel.objects.filter(id=id).first()
        if cart:
            cart.selected = selected
            cart.save()
            return Response({"msg":"修改成功"})
        return Response({"msg": "修改失败"})
class CartAllS(APIView):
    def put(self,request):
        user = request.data.get('user')
        selected = request.data.get('selected')
        carts = CartModel.objects.filter(user=user)
        if carts:
            for i in carts:
                i.selected = selected
                i.save()
            return Response({"msg":"修改成功"})
        else:
            return Response({"msg":"修改失败"})
class Delall(APIView):
    def delete(self,request):
        user = request.query_params.get('user')
        carts = CartModel.objects.filter(user=user)
        if carts:
            for i in carts:
                if(i.selected==1):
                    i.delete()
        return Response({"msg": "删除成功!"})
